// -----------------------------------------------------------------------
//  <copyright file="DaprEmailSender.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2022 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2022-12-25 22:23</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Dapr.Properties;
using DaprPlus.Net;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;


namespace DaprPlus.Dapr;

public class DaprEmailSender : IEmailSender
{
    private readonly DaprClient _daprClient;
    private readonly ILogger _logger;

    /// <summary>
    /// 初始化一个<see cref="DaprEmailSender"/>类型的新实例
    /// </summary>
    public DaprEmailSender(IServiceProvider provider)
    {
        _daprClient = provider.GetRequiredService<DaprClient>();
        _logger = provider.GetLogger<DaprEmailSender>();
    }

    /// <summary>
    ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
    ///     directly from your code. This API may change or be removed in future releases.
    /// </summary>
    public async Task SendAsync(string email, string subject, string htmlMessage)
    {
        try
        {
            var metadata = new Dictionary<string, string>()
            {
                ["emailFrom"] = "noreply@dapr.plus",
                ["emailTo"] = email,
                ["subject"] = subject,
            };
            await _daprClient.InvokeBindingAsync("Fsb-email", "create", htmlMessage, metadata);
            _logger.LogInformation(ResDapr.Format_SendEmail_Success, email);
            
        }
        catch (Exception e)
        {
            _logger.LogError(ResDapr.Format_SendEmail_Fail, email, e);
            throw;
        }
    }
}
